import React, { useRef, useEffect, useState } from 'react';
import ProForm, { ModalForm, ProFormText, ProFormSelect, ProFormRadio } from '@ant-design/pro-form';
import { OptType } from '@/utils/constants';
import { Button, FormInstance, Popconfirm } from 'antd';
import { useModel } from 'umi';
import { showMsg } from '@/utils/utils';
import { isNull } from '@antv/util';
import { getRoleList } from '@/services/permissions/api';

const OptForm: React.FC<any> = (props) => {
  const {
    handleModalVisible,
    handleAdd,
    superAdmin,
    optType = OptType.ADD,
    record = {},
  } = props;
  const formRef = useRef<FormInstance>();

  const [isSuper, setIsSuper] = useState<boolean>(false);

  const { initialState } = useModel('@@initialState');

  // const myStaffCode = isNull(initialState?.currentUser?.super_oper_entity) ? initialState?.currentUser?.staff_code : initialState?.currentUser?.super_oper_entity?.staff_code;
  const myStaffCode = initialState?.currentUser?.staff_code || '';

  // 角色列表
  const [roleList, setRoleList] = useState<{ label: string; value: string; }[]>([]);

  const fetchRole = (dept_code) => {
    getRoleList({ current: 1, pageSize: 99999, dept_code }).then((res: PERMISSIONSAPI.RoleList) => {
      const data = res?.record_list?.map((item) => {
        return {
          label: item.role_name as string,
          value: item.role_id as string,
          dept_code: item.dept_code as string
        }
      });
      setRoleList(data || []);
    }).catch(err => {
      showMsg(err?.data?.errmsg);
    })
  }

  useEffect(() => {
    if (isNull(record.dept_code)) {
      fetchRole('')
    } else {
      fetchRole(record.dept_code);
    }
  }, [])

  return <ModalForm
    formRef={formRef}
    title="编辑账户信息"
    width="70%"
    visible
    layout="horizontal"
    modalProps={{
      maskClosable: false,

    }}
    onVisibleChange={handleModalVisible}
    onFinish={async (value) => {
      console.log('value', value.role_id, record)
      // return;
      const role = roleList.find(item => item.value === value.role_id) || {};
      console.log('role', role)
      // return;
      const success = await handleAdd({ ...record, ...value, role_id: role.value, role_name: role.label });
      if (success) {
        setTimeout(() => {
          handleModalVisible(false);
          window.location.reload();
        }, 100);
      }
    }}
    submitter={{
      render: (props, doms) => {
        return [
          <Button key="cancel" onClick={() => {
            handleModalVisible(false);
          }}>取消</Button>,

          optType === OptType.ADD && superAdmin && isSuper || superAdmin && superAdmin.role_id !== record.role_id && isSuper ? <Popconfirm
            key="save"
            title={
              <div>当前科室已配置超管账号，<br />是否将超管身份更换至此账号？</div>
            }
            okText="确认更换"
            cancelText="再想想"
            onConfirm={() => {
              props.form?.submit();
            }}
          >
            <Button key="save" type="primary">保存</Button>
          </Popconfirm> : <Button key="save" type="primary" onClick={() => { props.form?.submit(); }}>保存</Button>
        ]
      }
    }}
  >
    <ProForm.Group>
      <ProFormText
        rules={
          [
            {
              required: true
            }
          ]
        }
        label="员工工号"
        width="md"
        name="staff_code"
        initialValue={record.staff_code}
        disabled={optType === OptType.EDIT}
      />
      <ProFormText
        rules={
          [
            {
              required: true
            }
          ]
        }
        label="员工姓名"
        width="md"
        name="oper_name"
        initialValue={record.oper_name}
        disabled={optType === OptType.EDIT}
      />
    </ProForm.Group>

    <ProForm.Group>
      <ProFormText
        rules={
          [
            {
              required: true
            }
          ]
        }
        label="科室编号"
        width="md"
        name="dept_code"
        initialValue={record.dept_code}
        disabled={optType === OptType.EDIT}
      />
      <ProFormText
        rules={
          [
            {
              required: true
            }
          ]
        }
        label="科室名称"
        width="md"
        name="dept_name"
        initialValue={record.dept_name}
        disabled={optType === OptType.EDIT}
      />
    </ProForm.Group>

    <ProForm.Group>
      <ProFormSelect
        rules={
          [
            {
              required: true
            }
          ]
        }
        label="角色分配"
        placeholder="请选择"
        width="md"
        name="role_id"
        initialValue={record.role_id}
        options={roleList}
      />

    </ProForm.Group>

    {
      (record.staff_code ?? '' !== '') &&
      <ProForm.Group>
        <ProFormRadio.Group
          rules={
            [
              {
                required: true
              }
            ]
          }
          label="是否为管理员"
          name="identity_type"
          initialValue={record.identity_type || 'P'}
          fieldProps={{
            onChange: (e: any) => {
              setIsSuper(e.target.value);
            }
          }}
          options={[
            {
              label: '是',
              value: 'S'
            },
            {
              label: '否 （管理员账号会启用角色管理和账号管理功能，每科室限1名管理员）',
              value: 'P',
              disabled: record.staff_code === myStaffCode
            }
          ]}
        />
      </ProForm.Group>
    }

    <ProForm.Group>
      <ProFormRadio.Group
        rules={
          [
            {
              required: true
            }
          ]
        }
        label="账号状态"
        name="status"
        initialValue={record.status || 'N'}

        options={[
          {
            label: '启用',
            value: 'N'
          },
          {
            label: '停用',
            value: 'S',
            disabled: record.staff_code === myStaffCode
          }
        ]}
      />
    </ProForm.Group>

  </ModalForm>
}
export default OptForm;
